﻿using System;
using Common;
using Extensions.Consul;
using Microsoft.Extensions.Configuration;
using Winton.Extensions.Configuration.Consul;

namespace Extensions.ConfigurationCenter.Consul;

public static class AddConsulConfigurationCenter
{
    /// <summary>
    /// 使用consul的配置中心  加配置中心的数据加载到本地的configuration中 可以直接在appsetting类中来使用 并且修改后会自动更新
    /// </summary>
    /// <param name="configurationBuilder"></param>
    /// <returns></returns>
    public static IConfigurationBuilder AddConsulConfigurationCenterSetup(
        this IConfigurationBuilder configurationBuilder)
    {
        // consul是基于长轮训来做到 修改后更新配置的 这边直接使用别人做好轮子
        ArgumentNullException.ThrowIfNull(configurationBuilder);
        var consulOption = Appsettings.app<ConsulOption>("Consul");
        if (consulOption != null && consulOption.ConfigurationCenter&&!string.IsNullOrWhiteSpace(consulOption.CenterPath))
        {
            configurationBuilder.AddConsul(consulOption.CenterPath, options =>
            {
                // consul地址
                options.ConsulConfigurationOptions = configuration =>
                {
                    configuration.Address = new Uri(consulOption.ConsulAddress);
                };
                // 配置选项
                options.Optional = true;
                // 配置文件更新后重新加载
                options.ReloadOnChange = true;
                // 忽略加载报错
                options.OnLoadException = context =>
                {
                    context.Ignore = true;
                };
            });
        }
        
        return configurationBuilder;
    }
}